import type { IStack, IStructureItem } from '../type'

/**
 * @author hzq
 * @description 对象栈
 * @date 2024-11-3
 */
class Stack<T> implements IStack<T> {
  private items: IStructureItem<T>
  private count: number
  constructor() {
    this.items = {}
    this.count = 0
  }
  peek(): T | undefined {
    if (this.isEmpty()) return void 0
    return this.items[this.count - 1]
  }
  isEmpty(): boolean {
    return this.count <= 0
  }
  clear(): void {
    this.items = {}
    this.count = 0
  }
  get size(): number {
    return this.count
  }
  push(element: T) {
    this.items[this.count++] = element
    return this.count
  }
  pop() {
    if (this.isEmpty()) return void 0
    this.count--
    const res = this.items[this.count]
    delete this.items[this.count]
    return res
  }

  /**
   * 栈内容转字符串
   * @returns
   */
  toString() {
    if (this.isEmpty()) return 'stack is empty!'
    //@ts-ignore
    let res = this.items[0].toString()
    for (let i = 1; i < this.count; i++) {
      //@ts-ignore
      res = `${res},${this.items[i].toString()}`
    }
    return res
  }
}

export default Stack
